﻿#include "widget.h"

#include <QApplication>
#include <QtSingleApplication>
#include <QDebug>
#include <QFileInfo>
#include <QProcess>
#include <QDir>

LONG WINAPI MyUnhandledExceptionFilter(EXCEPTION_POINTERS* pExceptionInfo) {
    // 记录崩溃日志等操作
    qCritical() << "程序异常崩溃,开始异常重启";

    // 获取异常记录
    EXCEPTION_RECORD* exceptionRecord = pExceptionInfo->ExceptionRecord;

    // 记录异常代码和地址
    qCritical() << "Exception Code:" << exceptionRecord->ExceptionCode;
    qCritical() << "Exception Address:" << exceptionRecord->ExceptionAddress;

    // 如果有额外的异常信息，也可以记录下来
    for (DWORD i = 0; i < exceptionRecord->NumberParameters; ++i) {
        qCritical() << "Exception Information[" << i << "]:" << exceptionRecord->ExceptionInformation[i];
    }

    QString restartToolPath = QCoreApplication::applicationDirPath() + "/DelayedRestartProgress.exe";
    qDebug() << restartToolPath;
    QStringList params;
    params << QString::number(5);
    params << QApplication::applicationFilePath();
    qDebug() << params;
    if(QFileInfo::exists(restartToolPath)){
        bool success = QProcess::startDetached(restartToolPath, params);
        if (success) {
            // 退出当前程序
            qApp->exit();
        } else {
            qCritical() << "打开重启工具失败:" << restartToolPath;
        }
    }else{
        qCritical() << "找不到重启工具:" << restartToolPath;
    }

    return EXCEPTION_EXECUTE_HANDLER;
}


void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QString logDataTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd");
    QString logData = QDateTime::currentDateTime().toString("yyyy-MM-dd");

    QString logHead;
    QString message;
    switch(type)
    {
    case QtDebugMsg:
        logHead = QString("运行");
        message = QString("<a style='color:green;'>【%1 | %2】: %3</a>").arg(logHead).arg(logDataTime).arg(msg);
        break;
    case QtWarningMsg:
        logHead = QString("警告");
        message = QString("<a style='color:yellow;'>【%1 | %2】: %3</a>").arg(logHead).arg(logDataTime).arg(msg);
        break;
    case QtCriticalMsg:
        logHead = QString("严重");
        message = QString("<a style='color:red;'>【%1 | %2】: %3</a>").arg(logHead).arg(logDataTime).arg(msg);
        break;
    case QtFatalMsg:
        logHead = QString("致命");
        message = QString("<a style='color:red;'>【%1 | %2】: %3</a>").arg(logHead).arg(logDataTime).arg(msg);
    }
    QString logDirPath = qApp->applicationDirPath()+"/logs/";
    if(!QDir().exists(logDirPath)){
       QDir().mkpath(logDirPath);
    }
    QString logPath = QString(qApp->applicationDirPath()+"/logs/"+logData+"_log.html");

    QFile file(logPath);
    file.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text);
    QTextStream text_stream(&file);
    text_stream.setCodec("utf-8");
    text_stream << message << "<br/>";
    file.flush();
    file.close();
}

int main(int argc, char *argv[])
{
    //    QApplication a(argc, argv);
    QtSingleApplication a(qApp->applicationName()+"_ID",argc, argv);
    if(a.isRunning())//判断实例是否已经运行
    {
        qDebug()<<"this is already running";
        a.sendMessage("raise_window_noop", 4000); //4s后激活前个实例
        return 0;
    }

    // 设置顶级异常处理器
    SetUnhandledExceptionFilter(MyUnhandledExceptionFilter);

    // 安装日志
#ifndef QT_DEBUG
    qInstallMessageHandler(outputMessage);
#endif

    QApplication::setQuitOnLastWindowClosed(false);// 关闭最后一个窗口时程序不退出
    //注册类型
    qRegisterMetaType<int8_t>("int8_t");
    qRegisterMetaType<uint8_t>("uint8_t");
    qRegisterMetaType<int16_t>("int16_t");
    qRegisterMetaType<uint16_t>("uint16_t");
    qRegisterMetaType<int32_t>("int32_t");
    qRegisterMetaType<uint32_t>("uint32_t");
    qRegisterMetaType<int64_t>("int64_t");
    qRegisterMetaType<uint64_t>("uint64_t");

    // 创建并显示主窗口
    Widget w;
    a.setActivationWindow(&w,true);

    return a.exec();
}
